<template>
    <MenuPage
        :data="resData.list"
        :columns="columns"
        :title="' '"
        :page.sync="queryParams.pageIndex"
        :size.sync="queryParams.pageSize"
        :total="resData.total"
        :loading="resData.loading"
        @queryFun="getProjectTemplateList">
        <template slot="search">
            <Input
                clearable
                v-model.trim="queryParams.name"
                placeholder="验证模板名称"
                @on-change="debounceFn"
                style="width: 180px;margin-left: 15px;" />
            <Select filterable transfer 
                v-model="queryParams.verify" 
                placeholder="是否验证"
                filterable
                clearable
                style="width:150px;text-align: left;margin-left: 15px;" 
                @on-change="changePageNow(1)">
                <Option :value="0">未验证</Option>
                <Option :value="1">已验证</Option>
            </Select>
            <Button
                type="primary"
                ghost
                style="height: 32px;margin-left: 9px;"
                @click="refreshQueryParams()">
                <i class="el-icon-refresh-right" />
            </Button>
        </template>
        <Modal
            v-model="modalData.show"
            :title="`${isAdd ? '创建' : '修改'}验证模板`"
            @on-visible-change="changeVisible"
            class="my-modal">
            <Form 
                ref="formInline"
                :label-width="110"
                :model="formInline" 
                :rules="ruleInline">
                <FormItem prop="name" label="验证模板名称">
                    <Input clearable v-model="formInline.name" disabled></Input>
                </FormItem>
                <FormItem prop="verify"  label="是否验证">
                    <Select filterable transfer filterable clearable v-model="formInline.verify" placeholder="">
                        <Option :value="0">未验证</Option>
                        <Option :value="1">已验证</Option>
                    </Select>
                </FormItem>
                <FormItem prop="description"  label="描述">
                    <Input clearable v-model="formInline.description" type="textarea" :rows="3"></Input>
                </FormItem>
            </Form>
            <div slot="footer" class="footer">
                <Button @click="modalData.show = false">取消</Button>
                <Button @click="saveVulnerability" :loading="modalData.loading" type="primary">确定</Button>
            </div>
        </Modal>
    </MenuPage>
</template>
  
<script>
import { 
    getVerifyProjectTemplateList,
    updateVerifyProjectTemplate,
    deleteVerifyProjectTemplate,
    createProjectByVulnerabilityTemplate
} from '@/view/testPlatform/asset/api/vulnerabilityVerifyTemplate'
import { debounce } from '@/libs/utils'
import createTopo from '@/view/testPlatform/mixin/createTopo'
import { validateName } from '@/libs/reg'

export default {
    name: 'VulnerabilityTarget',
    components:{
    },
    mixins: [createTopo],
    data () {
        return {
            resData: {
                total: 0,
                list: [],
                loading: true
            },
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                name: '',
                verify: '',
                vulnerabilityId: this.publicVulnerability && this.publicVulnerability.id
            },
            columns: [
                {
                    title: '验证模板名称',
                    key: 'name',
                    tooltip: true,
                },
                {
                    title: '是否验证',
                    key: 'closeIssue',
                    render: (h, params) => {
                        return h('Tag', {
                            props: {
                                color: params.row.verify ? '#19be6b' : '#ed4014'
                            },
                            style: {
                                width: '80px',
                                'text-align': 'center'
                            }
                        }, params.row.verify ? '已验证' : '未验证')
                    }
                },
                {
                    title: '描述',
                    key: 'description',
                    tooltip: true,
                },
                {
                    title: '操作',
                    width: 160,
                    slot: 'action',
                    opList: [
                        {
                            txt: '修改',
                            on:{
                                click:(data) => {
                                    this.showAddModal(data)
                                }
                            },
                        },
                        {
                            txt: '快速验证',
                            on:{
                                click:(data) => {
                                    this.goToTopo(data)
                                }
                            },
                        },
                        {
                            txt: '删除',
                            tooltip: true,
                            type: 'delete',
                            title: '确定要删除吗？',
                            on:{
                                click:(data,e) => {
                                    this.deleteItem([data.id])
                                }
                            },
                            disabled: (data)=>data.isUsed
                        }
                    ]
                }
            ],
            modalData: {
                show: false,
                loading: false
            },
            formInline: {},
            ruleInline: {
                name: [
                    { required: true, message: `验证模板名称不能为空`, trigger: 'blur,change' },
                    { type:'string',max: 64,trigger:'blur,change',message:'最多输入64个字符' },
                    { validator:validateName, trigger: 'blur,change' }
                ],
                verify: [
                    { required: true, type: 'number', message: `镜像类型不能为空`, trigger: 'blur,change' }
                ]
            },
            isAdd: false
        }
    },
    computed:{

    },
    watch:{

    },
    props: {
        publicVulnerability: {
            type: Object,
            default: () => {}
        }
    },
    mounted(){
        this.getProjectTemplateList()
    },
    beforeDestroy() {
    },
    created(){
    },
    methods:{
        // 跳转至拓扑页面
        async goToTopo(obj) {
            // 不存在工程ID，或者工程Id已失效，使用镜像、配额实时创建
            let projectId = obj.projectId
            if (await this.notAvailable(projectId)) {
                this.createProject(obj.id)
            } else {
                this.toTopoPage(projectId)
            }
        },
        // 通过模板创建工程，绑定工程ID与漏洞验证模板记录的关联关系
        createProject(templateId) {
            createProjectByVulnerabilityTemplate(templateId).then(({ code, message, data }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.getProjectTemplateList()
                this.toTopoPage(data)
            })
        },
        // 跳转至topo页面
        toTopoPage(projectId) {
            window.openTrain(`/jjzzTopo/index.html#/ProjectViews?projectId=${projectId}`);
        },
        // 删除验证模板
        deleteItem(ids) {
            deleteVerifyProjectTemplate(ids).then(({ code, message }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.$Message.success(`删除验证模板成功`)
                // 删除后展示当前页，当前页没有数据展示前一页
                this.queryParams.pageIndex = (this.resData.list.length == ids.length && this.queryParams.pageIndex > 1) ?
                                this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
                this.getProjectTemplateList()
            }).catch(() => {
                this.$Message.error(`删除验证模板异常`)
            })
        },
        // 隐藏模态框时，重置表单数据
        changeVisible(type) {
            if (!type) {
                this.$refs.formInline.resetFields()
                this.modalData.loading = false
            }
        },
        // 修改漏洞验证模板
        saveVulnerability() {
          this.$refs.formInline.validate(valid => {
              if (valid) {
                  this.modalData.loading = true
                  updateVerifyProjectTemplate(this.formInline).then(({ code, message }) => {
                      if (code !== 1) {
                          this.$Message.warning(message)
                          return
                      }
                      // 创建成功
                      this.$Message.success(`${this.isAdd ? '创建' : '修改'}验证模板成功`)
                      this.modalData.show = false
                      this.refreshQueryParams()
                  }).catch(() => {
                      this.$Message.error(`${this.isAdd ? '创建' : '修改'}验证模板异常`)
                  }).finally(() => {
                      this.modalData.loading = false
                  })
              }
          })
        },
        // 展示创建、修改漏洞验证模板的模态框
        showAddModal(data) {
          this.modalData.show = true
          this.isAdd = !data
          data.verify = data.verify ? 1 : 0
          this.formInline = Object.assign({}, data)
        },
        // 重置搜索条件并查询数据
        refreshQueryParams() {
            this.queryParams = {
                pageIndex: 1,
                pageSize: 10,
                name: '',
                verify: '',
                vulnerabilityId: this.publicVulnerability && this.publicVulnerability.id
            }
            this.getProjectTemplateList()
        },
        // 防抖方法，用于输入型查询
        debounceFn: debounce(function() {
            this.changePageNow(1);
        }),
        // 查询指定页数据
        changePageNow(val) {
            this.queryParams.pageIndex = val;
            this.getProjectTemplateList();
        },
        // 查询漏洞验证模板列表
        getProjectTemplateList() {
            this.resData.loading = true
            getVerifyProjectTemplateList(this.queryParams).then(({ code, message, data }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.resData = {
                    total: data.total || 0,
                    list: data.items || []
                }
            }).catch(() => {
                this.$Message.error('获取验证环境模板异常')
            }).finally(() => {
                this.resData.loading = false
            })
        },
    }
}
</script>

<style scoped>
.inline {
    display: flex;
}
.inline /deep/ .ivu-form-item {
    width: 50%;
}
</style>